import * as vscode from 'vscode';

// 更新后的LLM分析结果接口
interface LLMAnalysisResult {
  analysis: string;           // 错误分析文本
  replaced_snippet: string;   // 需要被替换的原始代码片段
  suggestions: string;        // 修复后的代码
}

// 找到的代码块位置
interface CodeBlockMatch {
  startLine: number;          // 开始行号
  endLine: number;            // 结束行号
  originalText: string;       // 原始代码文本
  found: boolean;             // 是否找到匹配
  matchScore: number;         // 匹配得分 (0-1)
  matchType: 'exact' | 'fuzzy' | 'semantic' | 'none';
  originalLineCount: number;  // 原始代码行数
  suggestedLineCount: number; // 建议代码行数
}

/**
 * 增强的忽略注释匹配策略 - 支持灵活行数替换
 */
class FlexibleCommentIgnoreStrategy {
  name = '灵活忽略注释匹配';
  weight = 0.85;

  execute(snippet: string, document: vscode.TextDocument, errorLine: number): CodeBlockMatch {
    const cleanSnippet = this.removeComments(snippet);
    const searchRange = this.getSearchRange(document, errorLine, 8); // 扩大搜索范围
    
    let bestMatch: CodeBlockMatch = this.createNoMatch();

    // 尝试不同的行数组合进行匹配
    for (let startLine = searchRange.end; startLine >=searchRange.start ; startLine--) {
      // 尝试1-10行的不同组合
      for (let lineCount = 1; lineCount <= Math.min(10, document.lineCount - startLine); lineCount++) {
        const endLine = startLine + lineCount - 1;
        if (endLine >= document.lineCount) break;
        
        const candidateText = this.extractText(document, startLine, endLine);
        const cleanCandidate = this.removeComments(candidateText);
        
        const similarity = this.calculateSimilarity(cleanSnippet, cleanCandidate);
        
        
        // 如果找到更好的匹配，更新最佳匹配
        if (similarity > bestMatch.matchScore && similarity >= 0.6) {
          bestMatch = {
            startLine,
            endLine,
            originalText: candidateText,
            found: true,
            matchScore: similarity ,
            matchType: similarity >= 0.95 ? 'exact' : 'fuzzy',
            originalLineCount: lineCount,
            suggestedLineCount: 0 // 将在后续设置
          };
          console.log(lineCount, startLine,endLine,similarity,cleanCandidate)
        }
      }
    }
    console.log("best,match",bestMatch)
    return bestMatch;
  }

  private removeComments(text: string): string {
    return text
      .replace(/\/\/.*$/gm, '')           // 单行注释
      .replace(/\/\*[\s\S]*?\*\//g, '')   // 多行注释
      .replace(/\s+/g, ' ')               // 标准化空白
      .trim();
  }

  private calculateSimilarity(str1: string, str2: string): number {
    if (str1 === str2) return 1.0;
    if (str1.length === 0 && str2.length === 0) return 1.0;
    if (str1.length === 0 || str2.length === 0) return 0.0;

    // 结合多种相似度算法
    const jaccardSim = this.jaccardSimilarity(str1, str2);
    const levenshteinSim = this.levenshteinSimilarity(str1, str2);
    const tokenSim = this.tokenSimilarity(str1, str2);
    
    // 加权平均
    return (jaccardSim * 0.4 + levenshteinSim * 0.3 + tokenSim * 0.3);
  }

  private jaccardSimilarity(str1: string, str2: string): number {
    const set1 = new Set(str1.split(/\s+/));
    const set2 = new Set(str2.split(/\s+/));
    
    const intersection = new Set([...set1].filter(x => set2.has(x)));
    const union = new Set([...set1, ...set2]);
    
    return intersection.size / union.size;
  }

  private levenshteinSimilarity(str1: string, str2: string): number {
    const distance = this.levenshteinDistance(str1, str2);
    const maxLen = Math.max(str1.length, str2.length);
    return maxLen === 0 ? 1.0 : (maxLen - distance) / maxLen;
  }

  private levenshteinDistance(str1: string, str2: string): number {
    const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
    
    for (let i = 0; i <= str1.length; i++) matrix[0][i] = i;
    for (let j = 0; j <= str2.length; j++) matrix[j][0] = j;
    
    for (let j = 1; j <= str2.length; j++) {
      for (let i = 1; i <= str1.length; i++) {
        const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
        matrix[j][i] = Math.min(
          matrix[j][i - 1] + 1,     // deletion
          matrix[j - 1][i] + 1,     // insertion
          matrix[j - 1][i - 1] + indicator // substitution
        );
      }
    }
    
    return matrix[str2.length][str1.length];
  }

  private tokenSimilarity(str1: string, str2: string): number {
    const tokens1: string[] = str1.match(/\w+/g) || [];
    const tokens2: string[] = str2.match(/\w+/g) || [];
    
    if (tokens1.length === 0 && tokens2.length === 0) return 1.0;
    if (tokens1.length === 0 || tokens2.length === 0) return 0.0;
    
    const commonTokens = tokens1.filter((token: string) => tokens2.includes(token));
    return (2 * commonTokens.length) / (tokens1.length + tokens2.length);
  }

  private getSearchRange(document: vscode.TextDocument, centerLine: number, radius: number) {
    return {
      start: Math.max(0, centerLine - radius),
      end: Math.min(document.lineCount - 1, centerLine + radius)
    };
  }

  private extractText(document: vscode.TextDocument, startLine: number, endLine: number): string {
    const lines: string[] = [];
    for (let i = startLine; i <= endLine; i++) {
      lines.push(document.lineAt(i).text);
    }
    return lines.join('\n');
  }

  private createNoMatch(): CodeBlockMatch {
    return { 
      startLine: 0, 
      endLine: 0, 
      originalText: '', 
      found: false, 
      matchScore: 0, 
      matchType: 'none',
      originalLineCount: 0,
      suggestedLineCount: 0
    };
  }
}

/**
 * 灵活的智能代码匹配器 - 支持不同行数的代码替换
 */
class FlexibleCodeMatcher {
  private strategy = new FlexibleCommentIgnoreStrategy();

  /**
   * 主匹配方法 - 支持灵活行数匹配
   */
  findBestMatch(
    snippet: string, 
    document: vscode.TextDocument, 
    errorLine: number,
    suggestedCode: string
  ): CodeBlockMatch {
    console.log(`开始灵活忽略注释匹配，错误行: ${errorLine + 1}`);
    
    try {
      const match = this.strategy.execute(snippet, document, errorLine);
      
      if (match.found && match.matchScore > 0.3) {
        // 设置建议代码的行数
        match.suggestedLineCount = suggestedCode.split('\n').length;
        
        console.log(`${this.strategy.name}: 得分 ${match.matchScore.toFixed(2)}, 行 ${match.startLine + 1}-${match.endLine + 1}`);
        console.log(`行数变化: ${match.originalLineCount} → ${match.suggestedLineCount}`);
        return match;
      }
    } catch (error) {
      console.warn(`策略 ${this.strategy.name} 执行失败:`, error);
    }

    console.log('灵活忽略注释匹配策略未找到匹配');
    return { 
      startLine: 0, 
      endLine: 0, 
      originalText: '', 
      found: false, 
      matchScore: 0, 
      matchType: 'none',
      originalLineCount: 0,
      suggestedLineCount: suggestedCode.split('\n').length
    };
  }
}

/**
 * 灵活的代码修复建议管理器 - 支持不同行数的代码替换
 */
class FlexibleCodeFixSuggestionManager {
  private fixDecorations = new Map<string, vscode.TextEditorDecorationType>();
  private codeMatcher = new FlexibleCodeMatcher();
  private currentPanel: vscode.WebviewPanel | null = null;

  /**
   * 处理后端返回的LSP分析结果（主入口）
   */
  async processLSPAnalysisResult(
    analysisResult: LLMAnalysisResult,
    diagnostic: vscode.Diagnostic,
    document: vscode.TextDocument
  ): Promise<void> {
    try {
      console.log('开始处理LSP分析结果（灵活行数替换）');
      console.log('Analysis:', analysisResult.analysis);
      console.log('Replaced Snippet:', analysisResult.replaced_snippet);
      console.log('Suggestions:', analysisResult.suggestions);
      
      // 检查建议是否为空，如果为空则直接返回，不给出任何提示
      if (!analysisResult.suggestions || analysisResult.suggestions.trim() === '') {
        console.log('建议为空，不显示任何提示');
        return;
      }

      // 检查是否有有效的替换代码片段
      if (!analysisResult.replaced_snippet) {
        console.log('缺少替换代码片段，显示分析结果');
        this.showAnalysisOnlyModal(analysisResult);
        return;
      }

      // 使用灵活匹配器查找代码块
      const codeBlockMatch = this.codeMatcher.findBestMatch(
        analysisResult.replaced_snippet,
        document,
        diagnostic.range.start.line,
        analysisResult.suggestions
      );

      if (!codeBlockMatch.found || codeBlockMatch.matchScore < 0.3) {
        console.log('灵活匹配无法找到可信的代码匹配');
        await this.showFailedMatchPanel(analysisResult, diagnostic, document);
        return;
      }

      console.log(`找到匹配 (${codeBlockMatch.matchType}): 第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行, 得分: ${codeBlockMatch.matchScore.toFixed(2)}`);
      console.log(`行数变化: ${codeBlockMatch.originalLineCount} → ${codeBlockMatch.suggestedLineCount}`);

      // 显示修复建议
      await this.showFixSuggestionModal(codeBlockMatch, diagnostic, document, analysisResult);

    } catch (error) {
      console.error('处理LSP分析结果失败:', error);
      vscode.window.showErrorMessage('处理代码分析结果失败: ' + error);
    }
  }

  /**
   * 显示修复建议模态框
   */
  private async showFixSuggestionModal(
    codeBlockMatch: CodeBlockMatch,
    diagnostic: vscode.Diagnostic,
    document: vscode.TextDocument,
    analysisResult: LLMAnalysisResult
  ): Promise<void> {
    // 高亮要替换的代码块
    await this.highlightCodeBlock(codeBlockMatch, document);

    const lineRange = codeBlockMatch.startLine === codeBlockMatch.endLine 
      ? `第${codeBlockMatch.startLine + 1}行`
      : `第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行`;

    const confidenceText = this.getConfidenceText(codeBlockMatch);
    const lineChangeText = this.getLineChangeText(codeBlockMatch);

    const items: vscode.QuickPickItem[] = [
      {
        label: '🚀 应用修复',
        description: `替换 ${lineRange} ${lineChangeText}`,
        detail: `${confidenceText} - 灵活替换代码块 (支持不同行数)`
      },
      {
        label: '📋 查看详细对比',
        description: '在侧边栏查看替换前后的详细对比',
        detail: '打开详细视图，查看行数变化详情'
      },
      {
        label: '❌ 忽略建议',
        description: '关闭修复建议',
        detail: '不进行修复'
      }
    ];

    const selected = await vscode.window.showQuickPick(items, {
      placeHolder: '选择要执行的操作',
      title: `🔧 灵活代码修复建议 - ${lineRange} (${confidenceText}) ${lineChangeText}`
    });

    // 如果用户取消选择（selected为undefined），则清除高亮
    if (!selected) {
      this.clearHighlights(document);
      return;
    }

    if (selected.label === '🚀 应用修复') {
      await this.applyFlexibleCodeReplacement(codeBlockMatch, analysisResult.suggestions, document);
      vscode.window.showInformationMessage(`✅ 已替换 ${lineRange} 的代码 ${lineChangeText}`);
    } else if (selected.label === '📋 查看详细对比') {
      await this.showDetailedPanel(codeBlockMatch, diagnostic, document, analysisResult);
    } else {
      // 用户选择"忽略建议"时清除高亮
      this.clearHighlights(document);
      vscode.window.showInformationMessage('已忽略修复建议');
    }

    // 无论哪种操作完成后都清除高亮
    this.clearHighlights(document);
  }

  private getConfidenceText(match: CodeBlockMatch): string {
    const score = match.matchScore;
    if (score >= 0.9) return '高置信度';
    if (score >= 0.7) return '中等置信度';
    if (score >= 0.5) return '低置信度';
    return '不确定';
  }

  private getLineChangeText(match: CodeBlockMatch): string {
    const diff = match.suggestedLineCount - match.originalLineCount;
    if (diff === 0) return '(行数不变)';
    if (diff > 0) return `(+${diff}行)`;
    return `(${diff}行)`;
  }

  /**
   * 应用灵活的代码块替换 - 支持不同行数，正确处理缩进
   */
  private async applyFlexibleCodeReplacement(
    codeBlockMatch: CodeBlockMatch,
    suggestedCode: string,
    document: vscode.TextDocument
  ): Promise<void> {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document !== document) {
      throw new Error('当前编辑器与文档不匹配');
    }

    console.log(`应用灵活代码块替换: 第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行`);
    console.log(`行数变化: ${codeBlockMatch.originalLineCount} → ${codeBlockMatch.suggestedLineCount}`);
    console.log(`原代码块:\n${codeBlockMatch.originalText}`);
    console.log(`新代码块:\n${suggestedCode}`);

    // 获取替换区域的基础缩进
    const firstLineText = document.lineAt(codeBlockMatch.startLine).text;
    const baseIndentation = firstLineText.match(/^(\s*)/)?.[1] || '';
    
    // 处理建议代码的缩进，确保第一行也有正确的缩进
    const adjustedSuggestedCode = this.adjustCodeIndentation(suggestedCode, baseIndentation);

    // 创建替换范围：从开始行的开头到结束行的结尾
    const replaceRange = new vscode.Range(
      codeBlockMatch.startLine, 0,
      codeBlockMatch.endLine, document.lineAt(codeBlockMatch.endLine).text.length
    );

    // 执行替换
    await editor.edit(editBuilder => {
      editBuilder.replace(replaceRange, adjustedSuggestedCode);
    });

    // 计算新的光标位置
    const suggestedLines = adjustedSuggestedCode.split('\n');
    const newEndLine = codeBlockMatch.startLine + suggestedLines.length - 1;
    
    // 移动光标到替换区域的开始
    const newSelection = new vscode.Selection(
      codeBlockMatch.startLine, baseIndentation.length,
      codeBlockMatch.startLine, baseIndentation.length
    );
    editor.selection = newSelection;
    
    // 确保替换区域可见
    const revealRange = new vscode.Range(
      codeBlockMatch.startLine, 0,
      Math.min(newEndLine, document.lineCount - 1), 0
    );
    editor.revealRange(revealRange, vscode.TextEditorRevealType.InCenter);

    // 显示替换统计信息
    const lineDiff = codeBlockMatch.suggestedLineCount - codeBlockMatch.originalLineCount;
    if (lineDiff !== 0) {
      const changeDesc = lineDiff > 0 ? `增加了 ${lineDiff} 行` : `减少了 ${Math.abs(lineDiff)} 行`;
      vscode.window.showInformationMessage(`代码替换完成，${changeDesc}`);
    }
  }

  /**
   * 调整代码缩进 - 修复第一行缩进问题
   */
  private adjustCodeIndentation(code: string, baseIndentation: string): string {
    const lines = code.split('\n');
    if (lines.length === 0) return code;

    // 找到第一个非空行来检测原始缩进
    const firstNonEmptyLine = lines.find(line => line.trim().length > 0);
    if (!firstNonEmptyLine) return code;

    const originalIndentation = firstNonEmptyLine.match(/^(\s*)/)?.[1] || '';

    // 调整每一行的缩进，包括第一行
    return lines.map((line, index) => {
      if (line.trim().length === 0) {
        // 保持空行，但如果是最后一行且为空，则不添加缩进
        return index === lines.length - 1 ? '' : line;
      }

      // 移除原始缩进，添加新的基础缩进
      const withoutOriginalIndent = line.substring(originalIndentation.length);
      console.log("缩进",baseIndentation,withoutOriginalIndent)
      return baseIndentation + withoutOriginalIndent;
    }).join('\n');
  }

  /**
   * 高亮要替换的代码块
   */
  private async highlightCodeBlock(codeBlockMatch: CodeBlockMatch, document: vscode.TextDocument): Promise<void> {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document !== document) return;

    const decorationType = vscode.window.createTextEditorDecorationType({
      backgroundColor: new vscode.ThemeColor('editor.wordHighlightStrongBackground'),
      border: '2px solid',
      borderColor: new vscode.ThemeColor('editorInfo.foreground'),
      borderRadius: '4px',
      overviewRulerColor: new vscode.ThemeColor('editorInfo.foreground'),
      overviewRulerLane: vscode.OverviewRulerLane.Right
    });

    const lineChangeText = this.getLineChangeText(codeBlockMatch);
    const decoration: vscode.DecorationOptions = {
      range: new vscode.Range(
        codeBlockMatch.startLine, 0, 
        codeBlockMatch.endLine, document.lineAt(codeBlockMatch.endLine).text.length
      ),
      hoverMessage: `🔧 将要替换的代码块\n第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行\n匹配类型: 灵活忽略注释匹配\n置信度: ${(codeBlockMatch.matchScore * 100).toFixed(1)}%\n行数变化: ${codeBlockMatch.originalLineCount} → ${codeBlockMatch.suggestedLineCount} ${lineChangeText}\n\n${codeBlockMatch.originalText}`
    };

    editor.setDecorations(decorationType, [decoration]);
    
    const documentKey = document.uri.toString();
    this.fixDecorations.set(documentKey, decorationType);

    // 滚动到高亮的代码块
    const revealRange = new vscode.Range(
      codeBlockMatch.startLine, 0,
      codeBlockMatch.endLine, 0
    );
    editor.revealRange(revealRange, vscode.TextEditorRevealType.InCenter);
  }

  /**
   * 清除高亮
   */
  private clearHighlights(document: vscode.TextDocument): void {
    const documentKey = document.uri.toString();
    const decorationType = this.fixDecorations.get(documentKey);
    
    if (decorationType) {
      const editor = vscode.window.activeTextEditor;
      if (editor) {
        editor.setDecorations(decorationType, []);
      }
      decorationType.dispose();
      this.fixDecorations.delete(documentKey);
    }
  }

  /**
   * 显示详细分析面板
   */
  private async showDetailedPanel(
    codeBlockMatch: CodeBlockMatch,
    diagnostic: vscode.Diagnostic,
    document: vscode.TextDocument,
    analysisResult: LLMAnalysisResult
  ): Promise<void> {
    // 保存当前编辑器的引用和状态
    const originalEditor = vscode.window.activeTextEditor;
    const originalViewColumn = originalEditor?.viewColumn;
    const originalSelection = originalEditor?.selection;
    const documentUri = document.uri.toString();

    if (this.currentPanel) {
      this.currentPanel.dispose();
    }

    this.currentPanel = vscode.window.createWebviewPanel(
      'flexibleCodeReplacement',
      '🔧 灵活代码替换预览',
      { 
        viewColumn: vscode.ViewColumn.Beside, 
        preserveFocus: true
      },
      {
        enableScripts: true,
        retainContextWhenHidden: true,
        localResourceRoots: []
      }
    );

    this.currentPanel.webview.html = this.getDetailedPanelHTML(codeBlockMatch, diagnostic, analysisResult, document);

    // 处理用户交互
    this.currentPanel.webview.onDidReceiveMessage(async (message) => {
      try {
        switch (message.command) {
          case 'applyReplacement':
            // 确保在正确的编辑器中进行替换
            const targetEditor = await this.ensureCorrectEditor(document, originalViewColumn);
            if (targetEditor) {
              await this.applyFlexibleCodeReplacementWithEditor(targetEditor, codeBlockMatch, analysisResult.suggestions, document);
              const lineChangeText = this.getLineChangeText(codeBlockMatch);
              vscode.window.showInformationMessage(`✅ 已替换代码块 ${lineChangeText}`);
            } else {
              vscode.window.showErrorMessage('无法找到目标编辑器，替换失败');
            }
            break;
          case 'dismiss':
            this.clearHighlights(document);
            this.currentPanel?.dispose();
            break;
        }
        
        // 尝试恢复编辑器焦点
        await this.restoreEditorFocus(document, originalViewColumn, originalSelection);
      } catch (error) {
        console.error('处理面板消息失败:', error);
        vscode.window.showErrorMessage('操作失败: ' + error);
      }
    });

    // 面板关闭时清理
    this.currentPanel.onDidDispose(() => {
      this.clearHighlights(document);
      this.currentPanel = null;
    });

    // 确保原始编辑器保持焦点
    setTimeout(() => {
      this.restoreEditorFocus(document, originalViewColumn, originalSelection);
    }, 100);
  }

  /**
   * 生成详细面板HTML
   */
  private getDetailedPanelHTML(
    codeBlockMatch: CodeBlockMatch,
    diagnostic: vscode.Diagnostic,
    analysisResult: LLMAnalysisResult,
    document: vscode.TextDocument
  ): string {
    const errorLine = diagnostic.range.start.line + 1;
    const lineRange = codeBlockMatch.startLine === codeBlockMatch.endLine 
      ? `第${codeBlockMatch.startLine + 1}行`
      : `第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行`;

    const confidenceText = this.getConfidenceText(codeBlockMatch);
    const matchScorePercent = (codeBlockMatch.matchScore * 100).toFixed(1);
    const lineChangeText = this.getLineChangeText(codeBlockMatch);
    const lineDiff = codeBlockMatch.suggestedLineCount - codeBlockMatch.originalLineCount;

    return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
        }
        .header {
            text-align: center;
            padding-bottom: 20px;
            border-bottom: 2px solid var(--vscode-editorInfo-foreground);
            margin-bottom: 25px;
        }
        .status-badge {
            display: inline-block;
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            padding: 6px 16px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .confidence-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
            margin-left: 8px;
        }
        .high-confidence { background-color: var(--vscode-terminal-ansiGreen); color: white; }
        .medium-confidence { background-color: var(--vscode-editorWarning-foreground); color: white; }
        .low-confidence { background-color: var(--vscode-editorError-foreground); color: white; }
        
        .line-change-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 10px;
            font-weight: bold;
            margin-left: 8px;
        }
        .line-increase { background-color: var(--vscode-terminal-ansiBlue); color: white; }
        .line-decrease { background-color: var(--vscode-terminal-ansiMagenta); color: white; }
        .line-same { background-color: var(--vscode-terminal-ansiGreen); color: white; }
        
        .section {
            background-color: var(--vscode-editor-inactiveSelectionBackground);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid var(--vscode-editorInfo-foreground);
        }
        .error-section { border-left-color: var(--vscode-editorError-foreground); }
        .analysis-section { border-left-color: var(--vscode-editorInfo-foreground); }
        .replacement-section { border-left-color: var(--vscode-terminal-ansiGreen); }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        .section-icon {
            margin-right: 10px;
            font-size: 20px;
        }
        .code-block {
            background-color: var(--vscode-textCodeBlock-background);
            border: 1px solid var(--vscode-textSeparator-foreground);
            border-radius: 6px;
            padding: 15px;
            margin: 10px 0;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
            white-space: pre;
            position: relative;
        }
        .original-code { 
            border-left: 4px solid var(--vscode-editorError-foreground);
            background-color: rgba(255, 0, 0, 0.1);
        }
        .suggested-code { 
            border-left: 4px solid var(--vscode-terminal-ansiGreen);
            background-color: rgba(0, 255, 0, 0.1);
        }
        .replaced-snippet { 
            border-left: 4px solid var(--vscode-editorWarning-foreground);
            background-color: rgba(255, 255, 0, 0.1);
        }
        
        .line-count-label {
            position: absolute;
            top: 5px;
            right: 10px;
            background-color: var(--vscode-badge-background);
            color: var(--vscode-badge-foreground);
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .diff-header {
            font-size: 14px;
            font-weight: 600;
            margin: 20px 0 10px 0;
            display: flex;
            align-items: center;
        }
        .diff-icon {
            margin-right: 8px;
            font-size: 16px;
        }
        
        .match-info {
            background-color: var(--vscode-editorWidget-background);
            border: 1px solid var(--vscode-editorInfo-foreground);
            border-radius: 6px;
            padding: 15px;
            margin: 15px 0;
        }
        .match-details {
            font-size: 13px;
            color: var(--vscode-descriptionForeground);
            margin-top: 8px;
        }
        
        .actions {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
            background-color: var(--vscode-editorWidget-background);
            border-radius: 8px;
        }
        .btn {
            display: inline-block;
            padding: 12px 24px;
            margin: 8px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }
        .btn-primary {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }
        .btn-primary:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
        .btn-secondary {
            background-color: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
        }
        .btn-secondary:hover {
            background-color: var(--vscode-input-background);
        }
        
        .replacement-preview {
            border: 2px dashed var(--vscode-editorInfo-foreground);
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            background-color: var(--vscode-input-background);
        }
        
        .line-numbers {
            display: inline-block;
            background-color: var(--vscode-badge-background);
            color: var(--vscode-badge-foreground);
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-family: monospace;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin: 15px 0;
        }
        .stat-item {
            text-align: center;
            padding: 10px;
            background-color: var(--vscode-editor-background);
            border-radius: 6px;
            border: 1px solid var(--vscode-textSeparator-foreground);
        }
        .stat-value {
            font-size: 18px;
            font-weight: bold;
            color: var(--vscode-editorInfo-foreground);
        }
        .stat-label {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
        }
        
        .strategy-badge {
            display: inline-block;
            background-color: var(--vscode-editorWarning-background);
            color: var(--vscode-editorWarning-foreground);
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .flexible-highlight {
            background: linear-gradient(45deg, 
                var(--vscode-terminal-ansiBlue), 
                var(--vscode-terminal-ansiMagenta));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-weight: bold;
        }
        
        h1, h2, h3 { margin-top: 0; }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔧 <span class="flexible-highlight">灵活代码替换预览</span></h1>
        <div class="status-badge">灵活匹配成功</div>
        <span class="confidence-badge ${this.getConfidenceClass(codeBlockMatch)}">${confidenceText}</span>
        <span class="line-change-badge ${this.getLineChangeClass(lineDiff)}">${lineChangeText}</span>
        <br><span class="strategy-badge">支持不同行数的智能替换</span>
        <p>智能忽略代码注释，支持灵活行数变化的代码替换</p>
    </div>

    <div class="section error-section">
        <div class="section-title">
            <span class="section-icon">❌</span>
            错误信息
        </div>
        <div><strong>位置:</strong> 第 ${errorLine} 行</div>
        <div><strong>消息:</strong> ${this.escapeHtml(diagnostic.message)}</div>
    </div>

    <div class="section analysis-section">
        <div class="section-title">
            <span class="section-icon">🧠</span>
            智能分析
        </div>
        <div style="white-space: pre-line;">${this.escapeHtml(analysisResult.analysis)}</div>
    </div>

    <div class="section replacement-section">
        <div class="section-title">
            <span class="section-icon">🔄</span>
            灵活代码替换详情
        </div>
        
        <div class="match-info">
            <div><strong>📍 替换位置:</strong> <span class="line-numbers">${lineRange}</span></div>
            <div class="stats-grid">
                <div class="stat-item">
                    <div class="stat-value">${matchScorePercent}%</div>
                    <div class="stat-label">匹配置信度</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">灵活匹配</div>
                    <div class="stat-label">匹配策略</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${codeBlockMatch.originalLineCount} → ${codeBlockMatch.suggestedLineCount}</div>
                    <div class="stat-label">行数变化</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${Math.abs(codeBlockMatch.startLine - (errorLine - 1))}</div>
                    <div class="stat-label">距错误行距离</div>
                </div>
            </div>
            <div class="match-details">
                <strong>🎯 灵活匹配特点:</strong><br>
                • 智能移除单行注释(//)和多行注释(/* */)<br>
                • 支持不同行数的代码替换（${codeBlockMatch.originalLineCount}行 → ${codeBlockMatch.suggestedLineCount}行）<br>
                • 使用多种相似度算法：Jaccard、Levenshtein、Token匹配<br>
                • 自动调整缩进以保持代码格式一致性
            </div>
        </div>

        <div class="replacement-preview">
            <h3>🔍 灵活代码替换预览</h3>
            
            <div class="diff-header">
                <span class="diff-icon">📤</span>
                后端提供的待替换代码片段:
            </div>
            <div class="code-block replaced-snippet">
                <div class="line-count-label">参考片段</div>
                ${this.escapeHtml(analysisResult.replaced_snippet)}
            </div>
            
            <div class="diff-header">
                <span class="diff-icon">🔍</span>
                在文档中找到的匹配代码块 (${codeBlockMatch.originalLineCount}行):
            </div>
            <div class="code-block original-code">
                <div class="line-count-label">${codeBlockMatch.originalLineCount} 行</div>
                ${this.escapeHtml(codeBlockMatch.originalText)}
            </div>
            
            <div class="diff-header">
                <span class="diff-icon">✨</span>
                替换后的代码 (${codeBlockMatch.suggestedLineCount}行):
            </div>
            <div class="code-block suggested-code">
                <div class="line-count-label">${codeBlockMatch.suggestedLineCount} 行</div>
                ${this.escapeHtml(analysisResult.suggestions)}
            </div>
        </div>
    </div>

    <div class="actions">
        <h3>执行灵活替换操作</h3>
        <p>将 ${codeBlockMatch.originalLineCount} 行代码替换为 ${codeBlockMatch.suggestedLineCount} 行代码</p>
        <button class="btn btn-primary" onclick="applyReplacement()">
            🚀 应用灵活替换 (${confidenceText}) ${lineChangeText}
        </button>
        <button class="btn btn-secondary" onclick="dismiss()">
            ❌ 取消操作
        </button>
    </div>

    <script>
        const vscode = acquireVsCodeApi();

        function applyReplacement() {
            vscode.postMessage({ command: 'applyReplacement' });
        }

        function dismiss() {
            vscode.postMessage({ command: 'dismiss' });
        }

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 'Enter':
                        e.preventDefault();
                        applyReplacement();
                        break;
                    case 'Escape':
                        e.preventDefault();
                        dismiss();
                        break;
                }
            }
        });
    </script>
</body>
</html>`;
  }

  private getConfidenceClass(match: CodeBlockMatch): string {
    const score = match.matchScore;
    if (score >= 0.9) return 'high-confidence';
    if (score >= 0.7) return 'medium-confidence';
    return 'low-confidence';
  }

  private getLineChangeClass(lineDiff: number): string {
    if (lineDiff > 0) return 'line-increase';
    if (lineDiff < 0) return 'line-decrease';
    return 'line-same';
  }

  /**
   * 显示分析结果（当无法匹配时）
   */
  private async showAnalysisOnlyModal(analysisResult: LLMAnalysisResult): Promise<void> {
    const message = `智能分析结果:\n${analysisResult.analysis}\n\n修复建议:\n${analysisResult.suggestions}`;
    
    await vscode.window.showInformationMessage(
      message.length > 200 ? message.substring(0, 200) + '...' : message,
      { modal: true },
      '确定'
    );
  }

  /**
   * 显示匹配失败面板
   */
  private async showFailedMatchPanel(
    analysisResult: LLMAnalysisResult,
    diagnostic: vscode.Diagnostic,
    document: vscode.TextDocument
  ): Promise<void> {
    const choice = await vscode.window.showWarningMessage(
      '🔍 灵活匹配策略无法找到可信的代码匹配 (得分低于阈值)',
      { modal: false },
      '查看详细分析',
      '忽略'
    );

    if (choice === '查看详细分析') {
      this.showAnalysisOnlyModal(analysisResult);
    }
  }

  /**
   * 确保使用正确的编辑器进行代码替换
   */
  private async ensureCorrectEditor(
    document: vscode.TextDocument,
    preferredViewColumn?: vscode.ViewColumn
  ): Promise<vscode.TextEditor | undefined> {
    // 首先检查当前活动编辑器是否是目标文档
    const activeEditor = vscode.window.activeTextEditor;
    if (activeEditor && activeEditor.document.uri.toString() === document.uri.toString()) {
      return activeEditor;
    }

    // 如果当前编辑器不是目标文档，尝试找到并激活正确的编辑器
    const visibleEditors = vscode.window.visibleTextEditors;
    const targetEditor = visibleEditors.find(editor => 
      editor.document.uri.toString() === document.uri.toString()
    );

    if (targetEditor) {
      // 找到了目标编辑器，激活它
      await vscode.window.showTextDocument(document, {
        viewColumn: targetEditor.viewColumn || preferredViewColumn,
        preserveFocus: false,
        preview: false
      });
      return vscode.window.activeTextEditor;
    }

    // 如果没有找到可见的编辑器，创建一个新的
    try {
      const editor = await vscode.window.showTextDocument(document, {
        viewColumn: preferredViewColumn || vscode.ViewColumn.One,
        preserveFocus: false,
        preview: false
      });
      return editor;
    } catch (error) {
      console.error('无法打开文档编辑器:', error);
      return undefined;
    }
  }

  /**
   * 使用指定编辑器应用代码替换
   */
  private async applyFlexibleCodeReplacementWithEditor(
    editor: vscode.TextEditor,
    codeBlockMatch: CodeBlockMatch,
    suggestedCode: string,
    document: vscode.TextDocument
  ): Promise<void> {
    if (!editor || editor.document !== document) {
      throw new Error('编辑器与文档不匹配');
    }

    console.log(`应用灵活代码块替换: 第${codeBlockMatch.startLine + 1}-${codeBlockMatch.endLine + 1}行`);
    console.log(`行数变化: ${codeBlockMatch.originalLineCount} → ${codeBlockMatch.suggestedLineCount}`);
    console.log(`原代码块:\n${codeBlockMatch.originalText}`);
    console.log(`新代码块:\n${suggestedCode}`);

    // 获取替换区域的基础缩进
    const firstLineText = document.lineAt(codeBlockMatch.startLine).text;
    const baseIndentation = firstLineText.match(/^(\s*)/)?.[1] || '';
    
    // 处理建议代码的缩进，确保第一行也有正确的缩进
    const adjustedSuggestedCode = this.adjustCodeIndentation(suggestedCode, baseIndentation);

    // 创建替换范围：从开始行的开头到结束行的结尾
    const replaceRange = new vscode.Range(
      codeBlockMatch.startLine, 0,
      codeBlockMatch.endLine, document.lineAt(codeBlockMatch.endLine).text.length
    );

    // 执行替换
    await editor.edit(editBuilder => {
      editBuilder.replace(replaceRange, adjustedSuggestedCode);
    });

    // 计算新的光标位置
    const suggestedLines = adjustedSuggestedCode.split('\n');
    const newEndLine = codeBlockMatch.startLine + suggestedLines.length - 1;
    
    // 移动光标到替换区域的开始
    const newSelection = new vscode.Selection(
      codeBlockMatch.startLine, baseIndentation.length,
      codeBlockMatch.startLine, baseIndentation.length
    );
    editor.selection = newSelection;
    
    // 确保替换区域可见
    const revealRange = new vscode.Range(
      codeBlockMatch.startLine, 0,
      Math.min(newEndLine, document.lineCount - 1), 0
    );
    editor.revealRange(revealRange, vscode.TextEditorRevealType.InCenter);

    // 显示替换统计信息
    const lineDiff = codeBlockMatch.suggestedLineCount - codeBlockMatch.originalLineCount;
    if (lineDiff !== 0) {
      const changeDesc = lineDiff > 0 ? `增加了 ${lineDiff} 行` : `减少了 ${Math.abs(lineDiff)} 行`;
      vscode.window.showInformationMessage(`代码替换完成，${changeDesc}`);
    }
  }

  /**
   * 恢复编辑器焦点
   */
  private async restoreEditorFocus(
    document: vscode.TextDocument,
    viewColumn?: vscode.ViewColumn,
    selection?: vscode.Selection
  ): Promise<void> {
    try {
      const editor = await vscode.window.showTextDocument(document, {
        viewColumn: viewColumn || vscode.ViewColumn.One,
        preserveFocus: false,
        preview: false
      });

      if (selection && editor) {
        editor.selection = selection;
        editor.revealRange(selection, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
      }
    } catch (error) {
      console.error('恢复编辑器焦点失败:', error);
    }
  }

  /**
   * HTML转义
   */
  private escapeHtml(text: string): string {
    return text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  /**
   * 清理资源
   */
  dispose(): void {
    for (const [, decorationType] of this.fixDecorations) {
      decorationType.dispose();
    }
    this.fixDecorations.clear();
    
    if (this.currentPanel) {
      this.currentPanel.dispose();
      this.currentPanel = null;
    }
  }
}

// 导出灵活代码修复管理器实例
export const flexibleCodeFixManager = new FlexibleCodeFixSuggestionManager();

/**
 * 处理后端LSP分析结果（灵活行数替换）
 */
export async function handleContextAnalysisResult(
  analysisResult: LLMAnalysisResult,
  diagnostic: vscode.Diagnostic,
  document: vscode.TextDocument
): Promise<void> {
  await flexibleCodeFixManager.processLSPAnalysisResult(analysisResult, diagnostic, document);
}

/**
 * 清理所有修复建议
 */
export function clearAllFlexibleFixSuggestions(): void {
  flexibleCodeFixManager.dispose();
}